package com.guashu.jaywayjsonpath.jasonPath;

import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class DemoJasonPath {
    public static void main(String[] args) {
        System.out.println("张三");
    }

    @Test
    public void testJsonPath_getElement() throws Exception {
        String json = readJsonFile();
        //使用JsonPath获取所有作者集合
        List<String> authors = JsonPath.read(json, "$.store.book[*].author");
        System.out.println("你好");
        System.out.println(authors);
    }

    /**
     *  JsonPath将自动尝试将结果强制转换为调用者期望的类型，如果出错将报出异常：
     * @throws Exception
     */
    @Test
    public void testJsonPath_Return() throws Exception {
        String json = readJsonFile();
        //Will throw an java.lang.ClassCastException
//        List<String> list = JsonPath.parse(json).read("$.store.book[0].author");
//        System.out.println(list);
        //Works fine
        String author = JsonPath.parse(json).read("$.store.book[0].author");
        System.out.println(author);
    }

    public static String readJsonFile() throws Exception{
        String jsonContent="";
        // 使用ClassPathResource加载json文件
        Resource resource = new ClassPathResource("jsonFile/exsample.json");
        // 检查资源是否存在
        if (resource.exists()) {
            try (InputStream inputStream = resource.getInputStream();
                 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                 BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {

                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append('\n');
                }
                // 读取文件内容
                 jsonContent = stringBuilder.toString();

            }
        } else {
            // 文件不存在的处理逻辑
            System.out.println("JSON文件不存在。");
        }
        return jsonContent;
    }
}
